//
//  XKLAppendViewController.m
//  GuiZiShouDuanZi
//
//  Created by xmg on 16/4/25.
//  Copyright © 2016年 xiao_kl. All rights reserved.
//

#import "XKLAppendViewController.h"
#import <SVProgressHUD.h>
#import <MJExtension.h>
#import <AFNetworking.h>
#import "XKLLeftItem.h"
#import "XKLLeftTableViewCell.h"
#import "XKLRightItem.h"
#import "XKLRightTableViewCell.h"
#import <MJRefresh.h>

static NSString *leftCellID=@"leftCell";
static NSString *rightCellID=@"rightCell";

@interface XKLAppendViewController ()<UITableViewDataSource,UITableViewDelegate>
/** 左边模型数组*/
@property (nonatomic,strong)NSArray * leftItems;

/** 左边tableView*/
@property (weak, nonatomic) IBOutlet UITableView *leftTableView;
/** 右边tableView*/
@property (weak, nonatomic) IBOutlet UITableView *rightTableView;

/*记录当前的参数,用来判断最后的是点击那个*/
@property (nonatomic,strong)NSDictionary *currentDic;

//会话管理者
@property (nonatomic,weak)AFHTTPSessionManager *manager;
@end

@implementation XKLAppendViewController

-(AFHTTPSessionManager *)manager{
    if (_manager==nil) {
        _manager=[AFHTTPSessionManager manager];
    }
    return _manager;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [SVProgressHUD show];
    
    
    self.navigationItem.title=@"推荐关注";
    
    [self upTableView];
    [self leftSession];
    
    
    
}

-(void)upTableView{
    //左边tableview注册
    [self.leftTableView registerNib:[UINib nibWithNibName:NSStringFromClass([XKLLeftTableViewCell class]) bundle:nil] forCellReuseIdentifier:leftCellID];
    [self.rightTableView registerNib:[UINib nibWithNibName:NSStringFromClass([XKLRightTableViewCell class]) bundle:nil] forCellReuseIdentifier:rightCellID];
    self.rightTableView.rowHeight=70;
    
    self.automaticallyAdjustsScrollViewInsets=NO;
    
    //自己设置内嵌
    self.leftTableView.contentInset=UIEdgeInsetsMake(64, 0, 0, 0);
    self.rightTableView.contentInset=self.leftTableView.contentInset;
    
    //给rightTableView添加头部和尾部
    self.rightTableView.mj_header=[MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(rightSession)];
    
    self.rightTableView.mj_footer=[MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(updateSession)];
    self.rightTableView.tableFooterView.hidden=YES;
}

//上啦刷新
-(void)updateSession{
    
    //获取当前模型
    XKLLeftItem *leftItem=self.leftItems[self.leftTableView.indexPathForSelectedRow.row];
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    dic[@"a"]=@"list";
    dic[@"c"]=@"subscribe";
    dic[@"category_id"]=@(leftItem.ID);
    dic[@"page"]=@(leftItem.currentPage+1);
    leftItem.currentPage+=1;
    
    [self.manager GET:@"http://api.budejie.com/api/api_open.php" parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [leftItem.rightItems addObjectsFromArray:[XKLRightItem mj_objectArrayWithKeyValuesArray:responseObject[@"list"]]];
        
        //判断状态
        [self opinion];
        
        //刷新列表
        [self.rightTableView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self.rightTableView.mj_header endRefreshing];
        [SVProgressHUD showErrorWithStatus:@"刷新失败"];
    }];

}

//下拉刷新
-(void)rightSession{
    
    XKLLeftItem *leftItem=self.leftItems[self.leftTableView.indexPathForSelectedRow.row];
    
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    dic[@"a"]=@"list";
    dic[@"c"]=@"subscribe";
    dic[@"category_id"]=@(leftItem.ID);
    self.currentDic=dic;
    
    [self.manager GET:@"http://api.budejie.com/api/api_open.php" parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [leftItem.rightItems removeAllObjects];
        
        [leftItem.rightItems addObjectsFromArray:[XKLRightItem mj_objectArrayWithKeyValuesArray:responseObject[@"list"]]];
        //设置当前页和栏目数
        leftItem.currentPage=1;
        leftItem.total=[responseObject[@"total"] integerValue];
        //判断是否是当前的要刷新的
        if(self.currentDic!=dic) return;
        //判断状态
        [self opinion];
        
        //刷新列表
        [self.rightTableView reloadData];
        
        //加载完毕就结束刷新
        [self.rightTableView.mj_header endRefreshing];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        //加载不成功就结束刷新
        [self.rightTableView.mj_header endRefreshing];
        //提示
        [SVProgressHUD showErrorWithStatus:@"加载失败"];
        
    }];
}
//退出的时候也要取消
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    //取消HUD
    [SVProgressHUD dismiss];
    //该方法只会停止在队列里面的没有发出的请求
    [self.manager.operationQueue cancelAllOperations];
    //cancel方法可以停止当前正在的请求
    [self.manager.tasks makeObjectsPerformSelector:@selector(cancel)];
}


//左边网络请求
-(void)leftSession{
    //请求参数
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    dic[@"a"]=@"category";
    dic[@"c"]=@"subscribe";
    //加载数据
    [self.manager GET:@"http://api.budejie.com/api/api_open.php" parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //需要替换的成员变量
        [XKLLeftItem mj_setupReplacedKeyFromPropertyName:^NSDictionary *{
            return @{@"ID":@"id"};
        }];
        self.leftItems = [XKLLeftItem mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        
        [SVProgressHUD dismiss];
        
        //刷新界面
        [self.leftTableView reloadData];
        //进来选中第一个
        [self.leftTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:YES scrollPosition:UITableViewScrollPositionTop];
        //进行刷新数据
        [self.rightTableView.mj_header beginRefreshing];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [SVProgressHUD showErrorWithStatus:@"加载失败"];
    }];
}

//判断footer的状态
-(void)opinion{
    XKLLeftItem *leftItem=self.leftItems[self.leftTableView.indexPathForSelectedRow.row];
    
    //判断是否隐藏footer
    self.rightTableView.mj_footer.hidden = !leftItem.rightItems.count > 0;
    //判断是否要刷新
    if (leftItem.total==leftItem.rightItems.count)
    {
        [self.rightTableView.mj_footer endRefreshingWithNoMoreData];
    }else{
        [self.rightTableView.mj_footer endRefreshing];
    }
}

#pragma mark - UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView==self.leftTableView) {

        return self.leftItems.count;
    } else {
        XKLLeftItem *leftItem=self.leftItems[self.leftTableView.indexPathForSelectedRow.row];
        [self opinion];
        return leftItem.rightItems.count;
    }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (tableView==self.leftTableView) {
        
        XKLLeftTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:leftCellID];
        //取出模型
        XKLLeftItem *leftItem=self.leftItems[indexPath.row];
        cell.textLabel.text=leftItem.name;
        return cell;
        
    }else{
        
        XKLRightTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:rightCellID];
        XKLLeftItem *leftItem=self.leftItems[self.leftTableView.indexPathForSelectedRow.row];
        XKLRightItem *rightItem=leftItem.rightItems[indexPath.row];
        cell.item=rightItem;
        
        return cell;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //判断是那个tableview
    if (self.leftTableView==tableView) {
        
        //换不同频道的时候就要停止上拉刷新
        [self.rightTableView.mj_footer endRefreshing];
        
        
        [self.rightTableView reloadData];
        
        XKLLeftItem *leftItem=self.leftItems[indexPath.row];
        
        //一进来就进行一次下拉刷新
        if (!leftItem.rightItems.count) [self.rightTableView.mj_header beginRefreshing];
        
    }
    
    
    
}
@end
